package com.zcoj.mail.config;

import com.zcoj.mail.pojo.Mail;
import com.zcoj.mail.service.MailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;

import java.util.List;
import java.util.Properties;

@Slf4j
@Configuration
public class MailConfig {
    @Autowired
    private MailService mailService;
    private  String fromEmail;
    private  String password;

//    public MailConfig(@Value("${spring.mail.username}") String fromEmail,
//                      @Value("${spring.mail.password}") String password) {
//        this.fromEmail = fromEmail;
//        this.password = password;
//    }

    @Bean
    public JavaMailSender javaMailSender() {
        List<Mail> mailData = mailService.getMailData();

        if( mailData.size()!=0){
            Mail mail = mailData.get(0);
            fromEmail=mail.getMailName();
            password=mail.getMailPwd();

            log.info("javaMailSender:数据库获取邮箱配置成功:{}",mail);
        }else {
            log.error("javaMailSender:邮箱配置错误");
        }
        log.info("javaMailSender:邮箱配置成功");
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        mailSender.setHost("smtp.qq.com");
        mailSender.setPort(587);
        mailSender.setUsername(fromEmail);
        mailSender.setPassword(password);

        Properties properties = mailSender.getJavaMailProperties();
        properties.put("mail.smtp.auth", true);
        properties.put("mail.smtp.starttls.enable", true);
        return mailSender;
    }
}

